package com.hliushi.learn.listener;

import com.hliushi.learn.bean.Reader;
import com.hliushi.learn.service.ReaderService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.List;

/**
 * @ClassName MyServletContextListener
 * @Description 使用ApplicationListener来初始化一些数据到application域中的监听器
 * @Author liushi
 * @Date 2021/7/8 14:42
 * @Version V1.0
 **/
@Component
public class MyServletContextListener implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 先获取到application上下文
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

        // 获取对应的service
        ReaderService readerService = applicationContext.getBean(ReaderService.class);
        Reader reader = readerService.getMyReader();
        List<Reader> readerList = readerService.getReaderAll();
        // 获取application域对象, 将查到的信息放到application域中
        ServletContext application = applicationContext.getBean(ServletContext.class);
        application.setAttribute("reader", reader);
        application.setAttribute("readerList", readerList);
    }
}
